﻿using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using SIMS.Common.RestClient;
using System.Collections.Generic;
using SIMS.Common.Models;
using Newtonsoft.Json;
using SIMS.Shared.DTO;
using System.Threading.Tasks;
using SIMS.Shared.Models;
using Prism.Events;
using SIMS.Common.Events;

namespace SIMS.StudentModule.ViewModels
{
    public class StudentViewModel: BindableBase
    {
        private readonly IDialogService _dialogService;

        private readonly HttpRestClient _httpClient;

        private readonly IEventAggregator _eventAggregator;

        public StudentViewModel(IDialogService dialogService, HttpRestClient httpClient, IEventAggregator eventAggregator)
        {
            _dialogService = dialogService;
            _httpClient = httpClient;
            _eventAggregator = eventAggregator;

            this.pageNum = 1;
            this.pageSize = 20;
        }

        /// <summary>
        /// 学号
        /// </summary>
        private string no;

        public string No
        {
            get { return no; }
            set { SetProperty(ref no , value); }
        }

        /// <summary>
        /// 学生姓名
        /// </summary>
        private string name;

        public string Name
        {
            get { return name; }
            set { SetProperty(ref name, value); }
        }

        private ObservableCollection<StudentDTO> students;

        public ObservableCollection<StudentDTO> Students
        {
            get { return students; }
            set { SetProperty(ref students, value); }
        }

        private async void InitInfo()
        {
            Students = new ObservableCollection<StudentDTO>();
            var pagingModel = await GetStudents();
            if (pagingModel != null)
            {
                var entities = pagingModel.Items;
                Students.AddRange(entities);

                this.TotalCount = pagingModel.Count;
                this.TotalPage = (int)Math.Ceiling(this.TotalCount * 1.0 / this.pageSize);
            }
        }

        private async Task<PagingModel<StudentDTO>?> GetStudents() 
        {
            ShowLoading();
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters["no"] = this.No;
            parameters["name"] = this.Name;
            parameters["pageNum"] = this.pageNum;
            parameters["pageSize"] = this.pageSize;
           
            ApiRequest request = new ApiRequest();
            request.Method = RestSharp.Method.Get;
            request.Parameters = parameters;
            request.Route = Api.STUDENT_GETSTUDENTS;
            ResponseResultModel response = await _httpClient.Execute(request);
            StopLoading();
            if (response.code == 1)
            {
                var students = JsonConvert.DeserializeObject<PagingModel<StudentDTO>>(JsonConvert.SerializeObject(response.data));
                return students;
            }
            return null;
        }

        private void ShowLoading()
        {
            _eventAggregator.GetEvent<LoadingEvent>().Publish(true);
        }

        private void StopLoading()
        {
            _eventAggregator.GetEvent<LoadingEvent>().Publish(false);
        }

        private DelegateCommand loadedCommand;

        public DelegateCommand LoadedCommand
        {
            get
            {
                if (loadedCommand == null)
                {
                    loadedCommand = new DelegateCommand(Loaded);
                }
                return loadedCommand;
            }
        }

        private void Loaded()
        {
            InitInfo();
        }

        private DelegateCommand queryCommand;

        public DelegateCommand QueryCommand
        {
            get
            {
                if (queryCommand == null)
                {
                    queryCommand = new DelegateCommand(Query);
                }
                return queryCommand;
            }
        }

        private void Query()
        {
            this.pageNum = 1;
            this.InitInfo();
        }

        private DelegateCommand addCommand;

        public DelegateCommand AddCommand
        {
            get
            {
                if (addCommand == null)
                {
                    addCommand = new DelegateCommand(Add);
                }
                return addCommand;
            }
        }

        private void Add()
        {
            this._dialogService.ShowDialog("addEditStudent", null, AddEditCallBack, "MetroDialogWindow");
        }

        private void AddEditCallBack(IDialogResult dialogResult)
        {
            if (dialogResult != null && dialogResult.Result == ButtonResult.OK)
            {
                this.pageNum = 1;
                this.InitInfo();
            }
        }

        private DelegateCommand<object> editCommand;

        public DelegateCommand<object> EditCommand
        {
            get
            {
                if (editCommand == null)
                {
                    editCommand = new DelegateCommand<object>(Edit);
                }
                return editCommand;
            }
        }

        private void Edit(object obj) 
        {
            if (obj == null)
            {
                return;
            }
            var student = obj as StudentDTO;
            if (student == null)
            {
                MessageBox.Show("无效的学生ID");
                return;
            }
            
            IDialogParameters dialogParameters = new DialogParameters();
            dialogParameters.Add("student", student);
            this._dialogService.ShowDialog("addEditStudent", dialogParameters, AddEditCallBack, "MetroDialogWindow");
        }

        private DelegateCommand<object> deleteCommand;

        public DelegateCommand<object> DeleteCommand
        {
            get
            {
                if (deleteCommand == null)
                {
                    deleteCommand = new DelegateCommand<object>(Delete);
                }
                return deleteCommand;
            }
        }

        private async void Delete(object obj)
        {
            if (obj == null)
            {
                return;
            }
            var student = obj as StudentDTO;
            if (student == null)
            {
                MessageBox.Show("无效的学生ID");
                return;
            }
            if (MessageBoxResult.Yes != MessageBox.Show("Are you sure to delete?", "Confirm", MessageBoxButton.YesNo))
            {
                return;
            }
            bool flag = await DeleteStudent(student.Id);
            if (flag)
            {
                this.pageNum = 1;
                this.InitInfo();
            }
        }

        private async Task<bool> DeleteStudent(int id)
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters["Id"] = id;

            ApiRequest request = new ApiRequest();
            request.Method = RestSharp.Method.Delete;
            request.Parameters = parameters;
            request.Route = Api.STUDENT_DELETESTUDENT;
            ResponseResultModel response = await _httpClient.Execute(request);
            if (response.code == 1)
            {
                long r = (long)response.data;
                return r == 1;
            }
            return false;
        }

        /// <summary>
        /// 当前页码
        /// </summary>
        private int pageNum;

        public int PageNum
        {
            get { return pageNum; }
            set { SetProperty(ref pageNum , value); }
        }

        /// <summary>
        /// 每页显示多少条记录
        /// </summary>
        private int pageSize;

        public int PageSize
        {
            get { return pageSize; }
            set { SetProperty(ref pageSize , value); }
        }

        /// <summary>
        ///总条数
        /// </summary>
        private int totalCount;

        public int TotalCount
        {
            get { return totalCount; }
            set { SetProperty(ref totalCount , value); }
        }

        /// <summary>
        ///总页数
        /// </summary>
        private int totalPage;

        public int TotalPage
        {
            get { return totalPage; }
            set { SetProperty(ref totalPage , value); }
        }


        /// <summary>
        /// 跳转页
        /// </summary>
        private int jumpNum;

        public int JumpNum
        {
            get { return jumpNum; }
            set { SetProperty(ref jumpNum , value); }
        }

        /// <summary>
        /// 首页命令
        /// </summary>
        private DelegateCommand firstPageCommand;

        public DelegateCommand FirstPageCommand
        {
            get
            {
                if (firstPageCommand == null)
                {
                    firstPageCommand = new DelegateCommand(FirstPage);
                }
                return firstPageCommand;
            }

        }

        private void FirstPage()
        {
            MessageBox.Show("第一页");
        }

        /// <summary>
        /// 跳转页命令
        /// </summary>
        private DelegateCommand jumpPageCommand;

        public DelegateCommand JumpPageCommand
        {
            get
            {
                if (jumpPageCommand == null)
                {
                    jumpPageCommand = new DelegateCommand(JumpPage);
                }
                return jumpPageCommand;
            }
        }

        private void JumpPage() { 
            
        }

        /// <summary>
        /// 前一页
        /// </summary>
        private DelegateCommand prevPageCommand;

        public DelegateCommand PrevPageCommand
        {
            get
            {
                if (prevPageCommand == null)
                {
                    prevPageCommand = new DelegateCommand(PrevPage);
                }
                return prevPageCommand;
            }
        }

        private void PrevPage() { 
        
        }

        /// <summary>
        /// 下一页命令
        /// </summary>
        private DelegateCommand nextPageCommand;

        public DelegateCommand NextPageCommand
        {
            get {
                if (nextPageCommand == null) {
                    nextPageCommand = new DelegateCommand(NextPage);
                }
                return nextPageCommand; }
        }

        private void NextPage()
        {

        }
    }
}
